﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SerialBrowserBridge.Devices;
using SerialBrowserBridge.WebServer;
using System.Text.RegularExpressions;

namespace SerialBrowserBridge
{
    public partial class MainForm : Form
    {
        private WebServerCore _webServer = new WebServerCore();

        public MainForm()
        {
            InitializeComponent();

        }

        public string[] Arguments { get; set; }


        private void FormLoad(object sender, EventArgs e)
        {
            var useDefaultDevice = true;

            var device = Arguments.Select(s => s.ToLower()).FirstOrDefault(f => f.StartsWith("/device:"));
            if (device != null)
            {
                var serialRegex = new Regex(@"^/device:com(?<id>\d{1,2}),(?<baud>300|1200|2400|4800|9600|19200|38400|57600|115200)$");
                if (serialRegex.IsMatch(device))
                {
                    var matches = serialRegex.Matches(device);

                    var serialDevice = new SerialDevice
                    {
                        PortID = int.Parse(matches[0].Groups["id"].Value),
                        Baud = int.Parse(matches[0].Groups["baud"].Value)
                    };
                    useDefaultDevice = false;

                    _webServer.Device = serialDevice;
                    if (_webServer.Device.Initialize() == false)
                    {
                        MessageBox.Show(String.Format("Die serielle Schnittstelle {0} konnte nicht geöffnet werden. Bitte starten Sie die Applikation neu", serialDevice.PortID));
                    }
                }

                if (useDefaultDevice)
                {
                    var console = new ConsoleDevice();
                    console.Show();
                    _webServer.Device = console;
                    _webServer.Device.Initialize();
                }
            }
            
            _webServer.Initalize();
            _webServer.Device.ReadBlock += text => Invoke(new Action(delegate { webBrowser.Navigate(_webServer.URL); }));
            webBrowser.Navigate(_webServer.URL);
        }

        private void FormClose(object sender, FormClosedEventArgs e)
        {
            if (_webServer != null)
            {
                _webServer.Dispose();
                _webServer = null;
            }
        }
    }
}
